<template>
    <el-dialog title="添加班级" :visible.sync="addClassData.dialogFormVisible" size="tiny"  class="dialog-box11"  @close="close('dataForm')" >
        <el-form v-loading='loading' class="form-content"  :model="dataForm" :rules="rules" ref="dataForm" label-width="80px"  label-position='right'>
            <el-row :gutter="21" class="school-item">
                <el-col :span="24">
                    <el-form-item label="学校名称" prop="schoolName" :rules="rules.schoolName">
                        <el-autocomplete v-model="dataForm.schoolName" :fetch-suggestions="remoteMethod" :trigger-on-focus="true" placeholder="请输入关键词" @select="queryAllGrade" style="width:100%"></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="24" v-if="this.schoolType == '0'">
                    <el-form-item label="年级" prop="grade" :rules="rules.schoolName">
                        <el-select ref="sel1" v-model="dataForm.grade" clearable placeholder="请选择" style="width:100%;" @change="queryAllClass( dataForm.grade )">
                            <el-option v-for="item in gradeList" :key="item.pId" :label="item.sName" :value="item.pId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="21" class="school-item">
                <el-col :span="24">
                    <el-form-item label="班级名称" prop="classId" :rules="rules.schoolName">
                        <el-select ref="sel2" v-model="dataForm.classId" clearable placeholder="请选择" style="width:100%;">
                            <el-option v-for="item in classList" :key="item.classId" :label="item.className" :value="item.classId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        
        <div slot="footer" class="dialog-footer">
            <el-button @click="resetForm('dataForm')"> 取 消 </el-button>
            <el-button type="primary" @click="submitForm('dataForm')"> 确 定 </el-button>
        </div>
    </el-dialog>
</template>

<script>
    import { querySchoolByName } from 'api/common';
    import { insertClassInfo, getGrade, getClass } from 'api/studentMange';
    import { mapGetters } from 'vuex';
    export default {
        props: {
            addClassData: {
                default() {
                    return {
                        studentId: ''
                    }
                },
                required: true
            }
        },
        data() {
            return {
                loading: false,
                schoolLoading: false,
                schoolType: '0',
                schoolList: [],
                gradeList: [],
                classList: [],
                dataForm: {
                    schoolId: '',
                    schoolName: '',
                    grade: '',
                    classId: ''
                },
                rules: {
                    schoolName: [
                        { required: true, message: '内容不能为空', trigger: 'change' }
                    ]
                }
            }
        },
        mounted() {
            setTimeout(() => {
                this.$refs.sel1.handleResize();
                this.$refs.sel2.handleResize();
            }, 500);
        },
        computed: {
            ...mapGetters([
                'uid'
            ])
        },
        methods: {
            submitForm(dataForm) {
                this.$refs[dataForm].validate((valid) => {
                    if (valid) {
                        let userId = this.uid; // 用户ID
                        let studentId = this.addClassData.studentId;
                        let schoolId = this.dataForm.schoolId; // 所属学校id
                        let schoolName = this.dataForm.schoolName; // 所属学校名称
                        let grade = this.dataForm.grade; //  年级
                        let classNum = this.dataForm.classId; // 班级编号
                        this.loading = true;
                        insertClassInfo(userId, studentId, schoolId, schoolName, grade, classNum).then(response => {
                            this.loading = false;

                            if (response.data.status == 200) {
                                this.$message.success(response.data.errorMsg);
                                this.addClassData.dialogFormVisible = false;
                                this.$emit('search');

                                this.dataForm.schoolId = '';
                                this.dataForm.grade = '';
                                this.dataForm.classId = '';
                            } else {
                                this.$message.error(response.data.errorMsg);
                            }
                        }).catch(() =>{
                            this.loading = false;
                        })
                    }
                })
            },
            resetForm(dataForm) {
                this.addClassData.dialogFormVisible = false;
                this.$refs[dataForm].resetFields();
            },
            close(dataForm) {
                this.addClassData.dialogFormVisible = false;
                this.$refs[dataForm].resetFields();
            },

            // 模糊查询学校名称
            remoteMethod(query, cb) {
                query = query.trim();
                if(query==''){
                    cb([{value:'无数据'}]);
                    this.$nextTick(()=>{
                        let firstSelect=$('.el-autocomplete-suggestion__list li:first');
                        firstSelect.addClass('remoteMethodScy');
                    })
                }
                if (query) {
                    querySchoolByName(query).then(response => {
                        this.schoolList = response.data.content;
                    }).then(() => {
                        let results = this.schoolList.filter(this.createStateFilter(query));
                        clearTimeout(this.timeout);
                        this.timeout = setTimeout(() => {
                            if(results.length){
                                let firstSelect=$('.el-autocomplete-suggestion__list li:first');
                                firstSelect.removeClass('remoteMethodScy');
                                cb(results)
                            }else{
                                cb([{value:'无数据'}]);
                                this.$nextTick(()=>{
                                    let firstSelect=$('.el-autocomplete-suggestion__list li:first');
                                    firstSelect.addClass('remoteMethodScy')
                                })
                            }
                        }, 200 * Math.random());
                    });
                } else {
                    this.schoolType = '0';
                    this.dataForm.grade = '';
                    this.gradeList = [];
                    this.dataForm.classId = '';
                    this.classList = [];
                    cb([{value:'无数据'}]);
                    this.$nextTick(()=>{
                        let firstSelect=$('.el-autocomplete-suggestion__list li:first');
                        firstSelect.addClass('remoteMethodScy')
                    })
                }  
            },
            createStateFilter(query) {
                return (state) => {
                    state.value = state.schoolName; 
                    return (state.value.toLowerCase().includes(query.toLowerCase()));
                };
            },
        
            // 年级列表
            queryAllGrade(val) {
                this.dataForm.grade = '';
                this.gradeList = [];
                this.schoolType = val.schoolType;

                if(val.schoolId) {
                    this.dataForm.schoolId = val.schoolId;
                
                    if (this.schoolType == '1') {
                        let schoolId = this.dataForm.schoolId;
                        getClass(null, schoolId).then(response => {
                            this.classList = response.data.content;
                        });
                    } else {
                        getGrade(val.schoolId).then(response => {
                            this.gradeList = response.data.content;
                        })
                    }  
                } else {
                    this.dataForm.schoolName = '';
                    this.schoolType = '0';
                }
            },

            // 班级列表
            queryAllClass(gradeId) {
                this.dataForm.classId = '';
                this.classList = [];
    
                if (this.dataForm.grade) {
                    let schoolId = this.dataForm.schoolId;
                    getClass(gradeId, schoolId).then(response => {
                        this.classList = response.data.content;
                    })
                }
            }
        }
    }

</script>

<style lang="scss" scoped>
    .dialog-box11{
        .el-dialog__header{
            text-align:center;
            background:#f7f7f9;
            height:54px;
            .el-dialog__title{
                font-size:20px;
                color:#333;
            }
        }
        .form-content{
            width: 80%;
            margin: 0 auto; 
        }
        .dialog-footer{
            margin: 0 auto; 
            text-align:center;
        }
    }
</style>